<?php

declare(strict_types=1);

namespace App\Command\Dev;

use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Hyperf\Stringable\Str;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

#[Command]
class QuickCommand extends HyperfCommand
{
    public function __construct(protected ContainerInterface $container)
    {
        parent::__construct('dev:quick');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('New module model');
        $this->addArgument('table', InputArgument::REQUIRED, 'Which table you want to associated with the Model.');
        $this->addOption('folder', null, InputOption::VALUE_OPTIONAL, 'The path that you want the Model file to be generated.');
    }

    public function handle()
    {
        $folder = $this->getOption('folder');

        $argument = [
            '--uses' => 'App\Model\Model',
            '--path' => 'app/Model'.($folder?"/{$folder}":''),
            '--with-comments' => true,
            '--refresh-fillable' => true
        ];
        if ($this->input->hasArgument('table')) {
            $argument['table'] = Str::snake($this->input->getArgument('table'));
        }
        /** 生成模型 */
        $this->call('gen:model', $argument);

        $argument = [
            '--uses' => '',
            '--path' => 'app/Traits/Model'.($folder?"/{$folder}":'')
        ];
        if ($this->input->hasArgument('table')) {
            $argument['table'] = $this->input->getArgument('table');
        }
        /** 生成Traits */
        $this->call('gen:traits', $argument);

        $argument = [
            '--path' => 'app/Services'.($folder?"/{$folder}":'')
        ];
        if ($this->input->hasArgument('table')) {
            $argument['table'] = $this->input->getArgument('table');
        }
        /** 生成Services */
        $this->call('gen:services', $argument);

        if ($this->input->hasArgument('table')) {
            $argument = [
                'name' => ($folder?"{$folder}/":'').Str::studly($this->input->getArgument('table'))
            ];
            $this->call('gen:request', $argument);
        }
    }

    protected function getOption(string $name, $default = null)
    {
        $result = $this->input->hasOption($name)?
            $this->input->getOption($name):
            $default;

        return $result;
    }
}
